<?php

function vietdecode($str){
        if(!$str) return false;
        $unicode = array(
            'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
            'd'=>'đ|Đ',
            'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
            'i'=>'í|ì|ỉ|ĩ|ị|Í|Ì|Ỉ|Ĩ|Ị',
            'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ|Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
            'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
            'y'=>'ý|ỳ|ỷ|ỹ|ỵ|Ý|Ỳ|Ỷ|Ỹ|Ỵ',
				'-'=>'%',	
			'-'=>' ',			
		
			//'.'=>'...',
			''=>'\/',
			''=>'”|“|"|(|)|,',
        );
        foreach($unicode as $nonUnicode=>$uni) $str = preg_replace("/($uni)/i",$nonUnicode,$str);
return strtolower($str);
    }
	
	function Watermark($image_path, $watermark_path){
		$watermark_id = imagecreatefrompng($watermark_path);
		imagealphablending($watermark_id, false);
		imagesavealpha($watermark_id, true);
		
		$info_img = getimagesize($image_path);
		$info_wtm = getimagesize($watermark_path);
		$fileType = strtolower($info_img['mime']);
		
		$image_w 		= $info_img[0];
		$image_h 		= $info_img[1];
		$watermark_w	= $info_wtm[0];
		$watermark_h	= $info_wtm[1];
			
		switch($fileType){
			case	'image/gif':	return false;									break;
			case	'image/png': 	$image_id = imagecreatefrompng($image_path);	break;
			default:				$image_id = imagecreatefromjpeg($image_path);	break;
		}
		/* Watermark in the bottom right of image*/
		$dest_x  = ($image_w - $watermark_w); 
		$dest_y  = ($image_h  - $watermark_h);
		
		/* Watermark in the middle of image 
		$dest_x = round(( $image_height / 2 ) - ( $logo_h / 2 ));
		$dest_y = round(( $image_w / 2 ) - ( $logo_w / 2 ));
		*/
		imagecopy($image_id, $watermark_id, $dest_x, $dest_y, 0, 0, $watermark_w, $watermark_h);
		
		//override to image
		switch($fileType){
			case	'image/png': 	imagepng ($image_id, $image_path); 		break;
			default:				imagejpeg($image_id, $image_path); 		break;
		}       		 
		imagedestroy($image_id);
		imagedestroy($watermark_id);
		return true;
	}
	
//print stripUnicode("Chào mừng bạn đến với phpbasic.com");
// chao mung ban den voi phpbasic.com

// Make Keywords for Meta tag
function makeKey($key)
{
    if ($key=="") return false;
	$bad = array('"',"'",'“','”',',','  ');
	$key =  str_replace($bad,' ',$key);
	$s = array(' ',', ,','.,');
	return strip_tags(str_replace($s,', ',$key));
}

// Make Description for Meta tag
function makeDes($key)
{
    if ($key=="") return false;
	
	$bad = array('"',"'",'“','”');
	
	return strip_tags(str_replace($bad,' ',$key));
	
}

function strips($str){
        if(!$str) return false;
        $content = array(
		    '"'=>"'",
            '&quot;'=>'"',
        );
        foreach($content as $nonStags=>$tags) $str = preg_replace("/($tags)/i",$nonStags,$str);
return $str;
    }

function chuanhoa($str){
        if(!$str) return false;
        $content = array(
            '&lt;'=>'<',
            '&gt;'=>'>',
        );
        foreach($content as $nonStags=>$tags) $str = preg_replace("/($tags)/i",$nonStags,$str);
return strtolower($str);
    }



function islogin()
{
if (isset($_SESSION['user']) && $_SESSION['user']!='') return $_SESSION['user'];
return false;
}
function checkemail($email)
{
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) 
		return false;
	return true;
}
function count_record($table,$where_ext = ""){
  global $db;
  if (!$db) { return false; }
  $query = "SELECT count(*) FROM $table ";
  if($where_ext != "")
	  $query.= " WHERE " . $where_ext;
  $result = $db->query($query);
  if ($result) {
    $rows = mysql_fetch_row($result);
    return $rows[0];
  } else {
    return false;
  }
}
function insert($table,$fields_arr) {
  global $db;
  if (!$db) { return false; }
  $strfields="";
  $strvalues="";
  list($key, $val) = each($fields_arr);
  if(is_string($key))
	{
	$strfields = " ($key";
	$strvalues= $val;
	while(list($key, $val) = each($fields_arr))
		{
		$strfields.= ", $key";
		$strvalues.= ",". $val;
		}
	$strfields.=")";
	}
  else
	{
	$strvalues=$fields_arr[0];
    for($i=1;$i<count($fields_arr);$i++)
		{
	      $strvalues .= ", $fields_arr[$i]";
		}
  	}
  $query = "INSERT INTO $table $strfields VALUES ($strvalues)";
  return $db->query($query);
}
function validate_search_string($s) 
{
	$s = str_replace("%","",$s);
	$s = str_replace("_","",$s);
	$s = stripslashes($s);
	$s = str_replace("'","\'",$s);
	return $s;
} 
function cut_string($str,$len,$more){
       if ($str=="" || $str==NULL) return $str;
   if (is_array($str)) return $str;
   $str = trim($str);
     if (strlen($str) <= $len) return $str;
     $str = substr($str,0,$len);
     if ($str != "") {
          if (!substr_count($str," ")) {
                  if ($more) $str .= " ...";
                return $str;
            }
        while(strlen($str) && ($str[strlen($str)-1] != " ")) {
                $str = substr($str,0,-1);
            }
            $str = substr($str,0,-1);
            if ($more) $str .= " ...";
        }
        return $str;
}
function db_prepare_input($string) {
    if (is_string($string)) {
      return trim(stripslashes($string));
    } elseif (is_array($string)) {
      reset($string);
      while (list($key, $value) = each($string)) {
        $string[$key] = tep_db_prepare_input($value);
      }
      return $string;
    } else {
      return $string;
    }
  }
function not_null($value) {
    if (is_array($value)) {
      if (sizeof($value) > 0) {
        return true;
      } else {
        return false;
      }
    } else {
      if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
        return true;
      } else {
        return false;
      }
    }
  }
  
function random($min = null, $max = null) {
    static $seeded;
    if (!$seeded) {
      mt_srand((double)microtime()*1000000);
      $seeded = true;
    }
    if (isset($min) && isset($max)) {
      if ($min >= $max) {
        return $min;
      } else {
        return mt_rand($min, $max);
      }
    } else {
      return mt_rand();
    }
  }
  
function random_select($query) {
  	global $db;
    $random_product = '';
    $random_query = $db->query($query);
    $num_rows = $db->numRows($random_query);
    if ($num_rows > 0) {
      $random_row = rand(0, ($num_rows - 1));
      mysql_data_seek($random_query, $random_row);
      $random_product = $db->fetchNextObject($random_query);
    }
    return $random_product;
  }
  
function getListCat($catid="",$tbl=""){
	global $db;
	if (isset($_SESSION['log'])) $hide="1=1";
    $ret=array();
	if ($tbl=="") $tbl='news_categories';
    if ($catid=="") $catid=0;
	if ($where=="") $where="1=1";
	$split="==";
	$sql= "select * from $tbl where ";
	$sql.=" parent_id=$catid order by ordering ASC";
	$result = $db->query($sql);
	while (($row=$db->fetchNextObject($result)))
	{
		$ret[]=array($row->id,($catid==0?"":$split).$row->title);
		$getsub=getListCat($row->id,$tbl);
		foreach ($getsub as $sub)
			$ret[]=array($sub[0],$sub[1]);
	}
	return $ret;
}




function getCat($catid,$tbl){ 
	global $db;
    if ($catid=="") return false;
	$sql="select * from $tbl where id=$catid limit 1";
	$result = $db->query($sql);
	return $db->fetchNextObject($result);
}


function getDownloadCat($catid){ 
	global $db;
    if ($catid=="") return false;
	$sql="select * from download_categories where id=$catid limit 1";
	$result = $db->query($sql);
	return $db->fetchNextObject($result);
}

function getNewsC($id){
	global $db,$langid;
	if ($id=="") return false;
	$sql="select * from news_categories where id=$id limit 1";
	$result=$db->query($sql);
	return $db->fetchNextObject($result);
} 


function file_size($filepath) {
    $bytes = array("B", "KB", "MB", "GB", "TB", "PB");
    $size = @filesize($filepath);
    $i = 0;
    while ($size >= 1024) { 
        $size = $size/1024;
        $i++;
    }
    if ($i > 1) {
        return round($size,1)."&nbsp;".$bytes[$i];
    } else {
        return round($size,0)."&nbsp;".$bytes[$i];
    }
}
function getFileList($dirname="."){
		global $config;
		$list = array(); 
		if ($handle = opendir($dirname)) {
			while (false !== ($file = readdir($handle))) { 
				if (preg_match("/\.(jpe?g|gif|png|gz|sql)$/i",$file)) { 
					$list[] = $file;
				} 
			}
			closedir($handle); 
		}
		if($config['sortOrder'] == "nameASC"){
			sort($list);
			reset($list);
		}elseif($config['sortOrder'] == "nameDESC"){
			rsort($list);
			reset($list);
		}else{
			sort($list);
			reset($list);
		}
		return $list;
	}

function getFolderList($dirname="."){
		global $config;
		$list = array(); 
		if ($handle = opendir($dirname)) {
			while (false !== ($folder = readdir($handle))) { 
				if (!preg_match("/\.(|..|htaccess)$/i",$folder)) { 
					$list[] = $folder;
				} 
			}
			closedir($handle); 
		}
		if($config['sortOrder'] == "nameASC"){
			sort($list);
			reset($list);
		}elseif($config['sortOrder'] == "nameDESC"){
			rsort($list);
			reset($list);
		}else{
			sort($list);
			reset($list);
		}
		return $list;
	}
	
function action($title){
	global $_GET;
	if($title=='') return false;
	if(!empty($_GET['id'])) $action='Chỉnh sửa'; else  $action='Add new';
	echo '<h2>'.$action.' '.$title.'<h2>';
	return true;
}

function generate_menu($parent,$type="")
{

	$java_menu="";
	
	
		if ($type=="download")			$java_menu="dl_";
		if ($type=="news") 
		{
		$class_main="  class='mainlevel'  ";
		$class_sub=" class='sublevel'  ";
		}
		
        $has_childs = false;
        //this prevents printing 'ul' if we don't have subcategories for this category
        global $menu_array,$menu;
        //use global array variable instead of a local variable to lower stack memory requierment
        foreach($menu_array as $key => $value)
        {
			
			
			
			/*
			if($value['parent']!=0) {
			$cha = $menu_array[$value['parent']]['alias'].'/';
			$class = '';
		} 
		else {
		$cha='';
		$class = "{".$value["section"]."}"; // '{".$value["section"]."}';
		
		}  
			*/
		
		
		
                if ($value['parent'] == $parent) 
                {       
                        //if this is the first child print '<ul>'                       
                        if ($has_childs === false)
                        {
							
                                //don't print '<ul>' multiple times                             
                                $has_childs = true;
								
                                if($parent==0) $menu .= "<!-- xx@{$type}@DLxx -->
								";
								
								else 
								{ 
								$menu .= "<div id={$java_menu}menu{$value['parent']}  style=\"padding-left:10px;padding-bottom:0px;line-height:22px; background: url(./images/menu_sep.png) 0 100% repeat-x;margin-bottom:3px;DISPLAY: none\">
								";
									if ($type=="news") 	$class_main="  class='sublevel'  ";
								}
                        }
						
					//	if($parent==0) $value['id']='';
						$java="";
						if($parent==0 AND $type<>"product") $java="	onclick=\"return showhide{$java_menu}('{$value['id']}')\"";
						
						
						
						if($value['links']!=''){
						$link = '<a href="'. $value['links'] .'">';
						}else{
							if($value['section']!='home'){
							$link = '<a '.$class_main.' href="/'.$type.'/'.$value['id'].'-'.$cha.$value['alias'].'/"  '.$java.'>';
							}else{
							$link = '<a  href="/" '.$class.'>';
							}
						}	
						$menu .= '' .$link. $value['name'] . '</a><BR>';
                      
                        $menu .= '
						';
						  generate_menu($key,$type);
                        //call function again to generate nested list for subcategories belonging to this category
						
						
                }
        }
        
		if ($has_childs === true and $parent!=0 ) $menu .= '</div>
		';
		
		return $menu;
}

/*function create_content($content,$filehtm){
	$pathfile ="../module/html/".$filehtm;			
		$ft=fopen($pathfile,"w");	   		
		if(fwrite($ft,$content))
			return true;
		else
			return false;
}*/

function OptionList($sql,$sid){
	global $db;
	$result = $db->query($sql);
	$strTxt ='';
	while ($row=$db->fetchNextObject($result))
	{
		if($row->id==$sid)
		$strTxt .= "<option value=".$row->id." selected>".$row->title."</option>";
		else
		$strTxt .= "<option value=".$row->id.">".$row->title."</option>";
	}
	return $strTxt;
}


	
function SelectTags($value,$array){	
	foreach ($array as $key => $val) {
			if($value == $key) {
		   	$strTxt .= "<option value=".$key." selected>".$val."</option>";
			}else{
			$strTxt .= "<option value=".$key.">".$val."</option>";
			}
		}
	return $strTxt;	
}

?>